import grails.util.GrailsWebUtil
import javax.servlet.http.HttpServletResponse
import org.codehaus.groovy.grails.commons.ConfigurationHolder
import org.codehaus.groovy.grails.web.converters.AbstractConverter
import org.codehaus.groovy.grails.web.converters.Converter
import org.codehaus.groovy.grails.web.converters.exceptions.ConverterException


/**
* 
* FIXME add geozone
*
*/

class KML extends AbstractConverter implements Converter {
    static final String STYLE_DEFAULT = "DefaultStyle";
    static final String STYLE_START_MOTION = "StartMotionStyle";
    static final String STYLE_START_MOTION_LAST = "StartMotionLastStyle";
    static final String STYLE_IN_MOTION = "InMotionStyle";
    static final String STYLE_IN_MOTION_LAST = "InMotionLastStyle";
    static final String STYLE_STOP_MOTION = "StopMotionStyle";
    static final String STYLE_STOP_MOTION_LAST = "StopMotionLastStyle";

    static int[] ICON_RED_CAR_CIRCLE = [224, 224]
    static int[] ICON_GREEN_CAR = [192, 0]
    static int[] ICON_GREEN_CAR_CIRCLE = [192, 32]
    static int[] ICON_YELLOW_CAR = [224, 128]
    static int[] ICON_YELLOW_CAR_CIRCLE = [224, 160]
    static int[] ICON_RED_CAR = [224, 192]

    static String ct = '''application/vnd.google-earth.kml+xml kml'''

    Eventdata[] object
    String encoding;
    static final String DEFAULT_ENCODING = "utf-8";

    public KML() {
        Map config = ConfigurationHolder.getFlatConfig();
        Object enc = config.get("grails.converters.encoding");
        if ((enc != null) && (enc.toString().trim().length() > 0)) {
            this.encoding = enc.toString();
        } else {
            this.encoding = DEFAULT_ENCODING;
        }
    }


    public void setTarget(Object arg0) {
        this.object = arg0;
    }

    public void render(Writer writer) throws ConverterException {
        def eds = this.object;
        this.writeEvents_KML(writer, eds)
    }


    boolean writeEvents_KML(pout, evdata) throws IOException
    {
        // def writer = new StringWriter()
        def kml = new groovy.xml.MarkupBuilder(pout)

        // def device = evdata[0].device

        kml.kml(xmlns: "http://earth.google.com/kml/2.2") {
            Folder {
                //name(device.imeiNumber + new Date().getTime() + ".kml")
                name("" + new Date().getTime() + ".kml")
                open(1)
                //polyline
                Placemark {
                    name("autopath")
                    Style {
                        IconStyle {
                            color("ff0000ff")
                            scale(1)
                        }
                        LineStyle {
                            color("ff0000ff")
                            width(1)
                        }
                        PolyStyle {
                            color("ff0000ff")
                        }
                    }
                    LineString {
                        coordinates(
                                evdata.collect {
                                    event -> "" + event.longitude + "," + event.latitude + "," + "0,"
                                }.join()
                                )
                    }
                } //polyline

                evdata.eachWithIndex {
                    event, index ->
                    Placemark {
                        name(index + 1)
                        Style {
                            IconStyle {
                                Icon {
                                    href("http://maps.google.com/mapfiles/kml/pal4/icon57.png")
                                }
                            }
                        } //style
                        Point {
                            coordinates(
                                    "" + event.longitude + "," + event.latitude + "," + "0"
                                    )
                        }
                    } //placemark
                }
            }
        }
        
        pout.flush();
        return true;

    }

    void render(HttpServletResponse response) throws ConverterException {
        response.setContentType(GrailsWebUtil.getContentType(ct, this.encoding));
        try {
            def pwriter = response.getWriter();
            // pwriter.write('<?xml version="1.0" encoding="UTF-8"?>');
            render(pwriter);
        } catch (IOException e) {
            throw new ConverterException(e);
        }

    }
}